package com.platform.api.bzproject.controller;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.platform.api.bzproject.model.*;
import com.platform.api.bzproject.service.*;
import com.platform.api.bzproject.vo.ParamWallpaper;
import com.platform.api.bzproject.vo.TalentVo;
import com.platform.api.common.component.ImageCompressComponent;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.core.ResultCode;
import com.platform.common.core.oss.AttachFileService;
import com.platform.common.core.oss.OssProcess;
import com.platform.common.core.oss.VideoFirstFrame;
import com.platform.common.util.EncryptionUtil;
import com.platform.mp.config.WxMaConfiguration;
import com.platform.security.util.SecurityUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 源码联系微信：2549789059
 * @author guoyunfei on 2021/12/8 22:12
 * @className AuthMethodCOntroller  统一需要认证的方法
 * @description TODO
 * @Version 1.0
 */
@RestController
@RequestMapping("{appid}/u/my")
public class AuthMethodController {


    @Autowired
    private UserService userService;
    @Autowired
    private BzAllWallpaperService bzAllWallpaperService;

    @Autowired
    private IBzTalentService iBzTalentService;

    @Autowired
    private IBzTagsService iBzTagsService;
    @Autowired
    private BzClassificationService bzClassificationService;

    @Autowired
    private BzBaseInfoService bzBaseInfoService;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private IWallpaperTagsService iWallpaperTagsService;

    @Autowired
    private ImageCompressComponent imageCompressComponent;



    /**
     * 获取壁纸数量
     * @return
     */
    @GetMapping("getMyCount")
    public Result getMyCount(){
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        int count = bzAllWallpaperService.count(new QueryWrapper<BzAllWallpaper>().eq("openid", userId));
        return Result.success(count);
    }

    @GetMapping("/selectMyWallpaper")
    private Result selectMyWallpaper(BzAllWallpaper wallpaper, Integer pageNum, Integer pageSize, Integer order, @PathVariable String appid){

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        wallpaper.setOpenid(userId);
        if(null == pageNum){
            pageNum = 1;
        }
        if(null == pageSize){
            pageSize = Constant.PAGESIZE_WALlPAPER;
        }
        wallpaper.setAppid(null);
        //排序
        String orderBy = bzAllWallpaperService.getOrderBy(order);
        PageInfo<BzAllWallpaper> pageInfo = bzAllWallpaperService.selectAllWallpaper(wallpaper, pageNum, pageSize,orderBy);
        List<BzAllWallpaper> list = pageInfo.getList();
        pageInfo.setList(list);
        return Result.success(pageInfo);
    }

    /**
     * 我的邀请记录
     * @return
     */
    @GetMapping("selectInvitationRecord")
    public Result selectInvitationRecord(Integer offset,Integer status){
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId).last("limit 1"));
        if(null == talent){
            return Result.failure("获取用户信息失败");
        }

        Map<String,Object> map = new HashMap<>(6);
        map.put("recommenderWord",talent.getWord());
        map.put("status",status);

        PageInfo<TalentVo> pageInfo = iBzTalentService.selectInvitationRecord(map, offset);
        return Result.success(pageInfo);
    }

    /**
     * 置顶壁纸
     * @return
     */
    @GetMapping("topping/{id}")
    public Result topping(@PathVariable  Integer id,Integer topping){

        if(null == id){
            return Result.failure("操作失败");
        }

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        if(1 == topping){
            List<BzAllWallpaper> list = bzAllWallpaperService.list(
                    new QueryWrapper<BzAllWallpaper>().eq("openid", userId)
                            .eq("topping", 1)
            .eq("is_delete",1));
            if(list.size() >= 100){
                return Result.failure("置顶失败,最多置顶100张");
            }
        }

        BzAllWallpaper bzAllWallpaper = new BzAllWallpaper();
        bzAllWallpaper.setTopping(topping);
        bzAllWallpaper.setId(id);
        boolean update = bzAllWallpaperService.updateById(bzAllWallpaper);
        if(update){
            return Result.success(update);
        }
        return Result.failure("操作失败");
    }

    @GetMapping("basics")
    private Result getTags(@PathVariable String appid) throws IOException {

        Map<String,Object> map = new HashMap<>(6);
        List<BzTags> tags = iBzTagsService.list(
                new QueryWrapper<BzTags>().eq("status", 1));
        map.put("tags",tags);

        BzClassification bzClassification = new BzClassification();
        bzClassification.setEnable(1);
        //多账号时开放
        //bzClassification.setAppid(appid);
        List<BzClassification> bzClassifications = bzClassificationService.selectList(bzClassification);
        map.put("classify",bzClassifications);

        //获取小程序基本信息
        BzBaseInfo baseInfo = bzBaseInfoService.getOne(new QueryWrapper<BzBaseInfo>().eq("appid", appid).last("limit 1"));
        if(null != baseInfo){
            if(baseInfo.getUploadCount() > 0){

                String userId = null;
                try {
                    userId = SecurityUtils.getUser().getUserId();
                }catch (Exception e){
                    return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
                }
                //获取用户今日已上传壁纸数量
                int uploadedQuantity = bzAllWallpaperService.getUploadCount(userId);
                map.put("uploadedQuantity",uploadedQuantity);
            }
            //每日上传数量
            map.put("uploadCount",baseInfo.getUploadCount());
        }
        return Result.success(map);
    }


    @GetMapping("checkWordEdit")
    public Result checkWordEdit(String word){
        try {

            String userId = SecurityUtils.getUser().getUserId();

            BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("word", word));

            if(null == talent){
                return Result.success("口令可用");
            }

            if(userId.equals(talent.getUserid())){
                return Result.success("口令可用");
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"未登录");
        }
        return Result.failure("口令不可用");
    }

    @PostMapping("getTalentInfo")
    public Result getTalentInfo(){
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId));
            User user = userService.getUserByUserId(userId);

            talent.setVipAccount(user.getVipAccount());
            if(null != talent){
                return Result.success(talent);
            }
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"未登录");
        }

        return Result.failure("获取信息失败");
    }


    @PostMapping("updateTalent")
    public Result updateTalent(@RequestBody  BzTalent talent){
        try {
            String userId = SecurityUtils.getUser().getUserId();
            BzTalent check = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("word", talent.getWord()));

            if(null != check){
                if(!userId.equals(check.getUserid())){
                    return Result.failure("口令不可用");
                }
            }

            BzTalent checkPhone = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("phone", talent.getPhone()));

            if(null != checkPhone){
                if(!userId.equals(checkPhone.getUserid())){
                    return Result.failure("手机号不可用");
                }
            }

            BzTalent talent_o = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId));

            if(null == talent_o){
                return Result.failure("您不是创作者");
            }

            talent.setId(talent_o.getId());
            iBzTalentService.updateById(talent);
            iBzTalentService.updateRecommenderWord(talent.getWord(),talent_o.getWord());

            //修改用户账号密码
            User user = userService.getUserByUserId(talent_o.getUserid());
            //设置密码
            String password = EncryptionUtil.combinationEncryp(Constant.PASSWORD);
            user.setLoginPassword(password);
            user.setUserMobile(talent.getPhone());
            userService.updateById(user);

            return Result.success("修改成功");
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"未登录");
        }
    }

    @GetMapping("isCreator")
    public Result isCreator(){
        try {
            String userId = SecurityUtils.getUser().getUserId();

            BzTalent talentt = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId));

            if(null == talentt){
                return Result.failure("您不是创作者");
            }

            if(talentt.getStatus() != 2){
                return Result.failure("您不是创作者");
            }
            return Result.success();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"未登录");
        }
    }

    @PostMapping("updateTalentAvatar")
    public Result updateTalentAvatar(@RequestParam("file") MultipartFile file){
        try {
            String userId = SecurityUtils.getUser().getUserId();

            String domain = attachFileService.getDomain();
            String s = attachFileService.uploadFile(file,null);

            String s1 = domain+"/"+ s + OssProcess.getCompressTx(attachFileService.getOssType());
            BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId));
            talent.setPic(s1);
            iBzTalentService.updateById(talent);

            User userByUserId = userService.getUserByUserId(userId);
            userByUserId.setPic(s1);
            userService.updateById(userByUserId);
            return Result.success("修改成功");
        }catch (Exception e){
            return Result.failure("未登录");
        }
    }

    /**
     * @return
     */
    @GetMapping("/deleteImage/{id}")
    public Result deleteImage(@PathVariable Integer id){

        if(null == id){
            return Result.failure("删除失败");
        }

        //bzAllWallpaperService.removeById(id);
        BzAllWallpaper allWallpaper = bzAllWallpaperService.getById(id);
        allWallpaper.setIsDelete(0);
        allWallpaper.setTopping(0);
        bzAllWallpaperService.updateById(allWallpaper);

        return Result.success();
    }

    /**
     * @return
     */
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody Integer[] ids){

        if(null == ids){
            return Result.failure("请选择要删除的数据");
        }

        Collection<BzAllWallpaper> entityList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            BzAllWallpaper allWallpaper = new BzAllWallpaper();
            allWallpaper.setIsDelete(0);
            allWallpaper.setId(ids[i]);
            allWallpaper.setTopping(0);
            entityList.add(allWallpaper);
        }

        bzAllWallpaperService.updateBatchById(entityList);
        return Result.success();
    }

    /**
     * @return
     */
    @PostMapping("/setClassData/{twoClassId}")
    public Result setClassData(@RequestBody Integer[] ids,@PathVariable Integer twoClassId){

        if(null == ids){
            return Result.failure("请选择要设置的数据");
        }

        Collection<BzAllWallpaper> entityList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            BzAllWallpaper allWallpaper = new BzAllWallpaper();
            allWallpaper.setId(ids[i]);
            allWallpaper.setTwoClassId(twoClassId);
            entityList.add(allWallpaper);
        }

        bzAllWallpaperService.updateBatchById(entityList);
        return Result.success();
    }

    /**
     * 文件上传
     * @param file 文件对象
     * @return
     * @throws IOException
     */
    @PostMapping("uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure("请先登录在进行操作");
        }

        BzTalent bzTalent = iBzTalentService.getOne(
                new QueryWrapper<BzTalent>().eq("userid", userId)
                        .eq("status",2)
                        .last("limit 1"));
        if(null == bzTalent){
            return Result.failure("您不是创作者,请先申请");
        }

        file = imageCompressComponent.imageCompres(file);

        String filename = attachFileService.uploadFile(file, null);

        String fileUrl = attachFileService.getDomain() + "/" +filename;;

        return Result.success(fileUrl);
    }

    /**
     * 保存上传文件的数据-新
     */
    @PostMapping("saveUploadFiles")
    public Result saveUploadFiles(@PathVariable String appid,@RequestBody BzAllWallpaper bzAllWallpaper) throws IOException {
        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            bzAllWallpaper.setOpenid(userId);
        }catch (Exception e){
            return Result.failure("请先登录在进行操作");
        }
        bzAllWallpaper.setAppid(appid);
        BzTalent bzTalent = iBzTalentService.getOne(
                new QueryWrapper<BzTalent>().eq("userid", userId)
                        .eq("status",2)
                        .last("limit 1"));
        if(null == bzTalent){
            return Result.failure("您不是创作者,请先申请");
        }
        List<ParamWallpaper> paramWallpapers = bzAllWallpaper.getParamWallpaperList();
        for (int i = 0; i < paramWallpapers.size(); i++) {
            String imgUrl = paramWallpapers.get(i).getImage();
            String video = paramWallpapers.get(i).getVideo();
            bzAllWallpaper.setImage(imgUrl);
            //添加压缩参数
            String compress = OssProcess.getCompress(attachFileService.getOssType());
            //设置低画质图片
            bzAllWallpaper.setLowImageQuality(imgUrl + OssProcess.getCompressNoAd(attachFileService.getOssType()));
            bzAllWallpaper.setThumbnail(imgUrl + compress);
            bzAllWallpaper.setIsDelete(1);
            bzAllWallpaper.setCreateTime(new Date());
            bzAllWallpaper.setTime(new Date());
            bzAllWallpaper.setStatus(1);
            bzAllWallpaper.setOriginalVideo(StringUtils.isNotBlank(video) ? video : null);
            bzAllWallpaperService.save(bzAllWallpaper);
        }

        //添加数据到标签表
        Collection<WallpaperTags> tagsList = new ArrayList<>();
        String[] split = bzAllWallpaper.getTagsIds().split(",");
        for (int i = 0; i < split.length; i++) {
            WallpaperTags wt = new WallpaperTags();
            wt.setTid(Long.valueOf(split[i]));
            wt.setWid(bzAllWallpaper.getId());
            tagsList.add(wt);
        }
        iWallpaperTagsService.saveBatch(tagsList);

        return Result.success();
    }

    @PostMapping("saveWallpaper")
    public Result saveWallpaper(@RequestParam("file") MultipartFile file,BzAllWallpaper bzAllWallpaper) throws IOException, NoSuchAlgorithmException, KeyManagementException {

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
            if(StringUtils.isNotBlank(userId)){
                bzAllWallpaper.setOpenid(userId);
            }
        }catch (Exception e){
            return Result.failure("获取用户信息失败");
        }

        if(StringUtils.isEmpty(bzAllWallpaper.getOpenid())){
            return Result.failure("请先登录在进行操作");
        }

        BzTalent bzTalent = iBzTalentService.getOne(
                new QueryWrapper<BzTalent>().eq("userid", bzAllWallpaper.getOpenid())
                        .eq("status",2)
                        .last("limit 1"));
        if(null == bzTalent){
            return Result.failure("您不是创作者,请先申请");
        }

        String filename = attachFileService.uploadFile(file, null);

        String domain = attachFileService.getDomain();

        String fileUrl = domain + "/" +filename;

        //原始图片地址
        String oriFileUrl = fileUrl;

        //检查是否是图片
        if("2".equals(bzAllWallpaper.getClassType())){
            //获取视频首帧参数
            String firstFrame = VideoFirstFrame.getFirstFrame(attachFileService.getOssType());
            fileUrl = fileUrl + firstFrame;
            //设置低画质图片
            bzAllWallpaper.setLowImageQuality(oriFileUrl + VideoFirstFrame.getFirstFrameNoAd(attachFileService.getOssType()));

        }else{

            //添加压缩参数
            String compress = OssProcess.getCompress(attachFileService.getOssType());
            fileUrl = fileUrl + compress;
            //设置低画质图片
            bzAllWallpaper.setLowImageQuality(oriFileUrl + OssProcess.getCompressNoAd(attachFileService.getOssType()));

        }

        bzAllWallpaper.setImage(oriFileUrl);

        bzAllWallpaper.setThumbnail(fileUrl);

        bzAllWallpaper.setIsDelete(1);
        bzAllWallpaper.setCreateTime(new Date());
        bzAllWallpaper.setTime(new Date());

        bzAllWallpaper.setImgSize(file.getSize());

        if(3 != bzAllWallpaper.getStatus()){
            bzAllWallpaper.setStatus(1);
        }
        bzAllWallpaperService.save(bzAllWallpaper);

        //添加数据到标签表
        Collection<WallpaperTags> tagsList = new ArrayList<>();

        String[] split = bzAllWallpaper.getTagsIds().split(",");
        for (int i = 0; i < split.length; i++) {
            WallpaperTags wt = new WallpaperTags();
            wt.setTid(Long.valueOf(split[i]));
            wt.setWid(bzAllWallpaper.getId());
            tagsList.add(wt);
        }

        iWallpaperTagsService.saveBatch(tagsList);

        return Result.success();
    }


    @Autowired
    private WxMaService wxMaService;

    @GetMapping("/wxacode")
    private Result wxacode(@PathVariable  String appid) throws WxErrorException, IOException {

        String userId = null;
        try {
            userId = SecurityUtils.getUser().getUserId();
        }catch (Exception e){
            return Result.failure(ResultCode.WEB_401,"获取用户信息失败");
        }

        BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", userId).last("limit 1"));
        if(null == talent){
            return Result.failure("获取用户信息失败");
        }

        if(null != talent){
            if(StringUtils.isNotBlank(talent.getQrCode())){
                return Result.success(talent.getQrCode());
            }
        }

        // 设置小程序二维码线条颜色为黑色
        WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
        // 获取小程序二维码生成实例
        WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();

        File file = wxMaQrcodeService.createWxaCodeUnlimit(""+talent.getWord(),"pages/apply/apply" ,  430, false, lineColor, false);

        //File 转 MultipartFile
        InputStream inputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);

        //上传阿里云 oss
        String s = attachFileService.getDomain() + File.separatorChar + attachFileService.uploadFile(multipartFile,"jpg");

        if(null != s){
            talent.setQrCode(s);
            iBzTalentService.updateById(talent);
        }

        return Result.success(s);
    }

}
